/*******************************************************************************
 * This software is subject to the terms of the GNU LESSER GENERAL PUBLIC LICENSE
 * Agreement, available at the following URL:
 * http://www.gnu.org/licenses/lgpl.html
 * Copyright (c) 2012, 2013  Feng Jianguang.
 * All rights reserved. 
 * You must accept the terms of that agreement to use this software.
 *******************************************************************************/
package com.brokenet.docs;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.brokenet.core.utils.FileUtils;

public class XuiOutput {
	static Pattern pattern = Pattern.compile("xclick=\"[^\"]*\"");

	public static void main(String[] args) {
		new XuiOutput().output();
	}

	String p = "http://localhost:8060";
	String[] enterUrl = new String[] { "brokenet_website",
			"brokenet_website_download", "brokenet_website_document",
			"brokenet_website_aboutus","brokenet_website_product" };

	boolean scan = false;

	private String session_value = null;

	File createFile(String path) {
		int i = path.indexOf("?");
		if (i >= 0)
			path = path.substring(0, i);

		File f = new File(path);
		f.getParentFile().mkdirs();
		try {
			f.createNewFile();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return f;
	}

	String getUrl(String path) {
		return p + path;
	}

	public void output() {
		for (String i : enterUrl) {
			requestAndSave("/dynamic/xui/tpl/" + i);
		}
	}

	void requestAndSave(String path) {
		try {
			System.out.println(path);

			URL url = new URL(getUrl(path));
			URLConnection conn = url.openConnection();
			if (session_value != null) {
				conn.setRequestProperty("Cookie", session_value);
			}
			List<String> lines = FileUtils.readLines(conn.getInputStream(),
					"UTF-8");
			if (session_value == null) {
				session_value = conn.getHeaderField("Set-Cookie");
			}

			File f = createFile(path);
			FileUtils.save(f, lines);
			if (scan)
				scan(lines);

		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	void scan(List<String> str) {

		for (String s : str) {
			Matcher matcher = pattern.matcher(s);
			while (matcher.find()) {
				String g = matcher.group();
				String v = g.substring("xclick=\"".length(), g.length() - 1);

				requestAndSave(v);

			}
		}
	}

}
